class Cart < ActiveRecord::Base
  has_many :cart_items
  has_many :artwork, :through => :cart_items
  
  def total_price
    cart_items.inject(0) {|sum, n| n.price * n.amount + sum}
  end
  
  def total_items
    cart_items.inject(0) {|sum, n| n.amount + sum}
  end
  
  def add(artwork_id)
    items = cart_items.find_all_by_artwork_id(artwork_id)
    artwork = Artwork.find(artwork_id);
    
    if items.size < 1
      ci = cart_items.create(:artwork_id => artwork_id,
                             :amount => 1,
                             :price => artwork.price)
    else
      ci = items.first
      ci.update_attribute(:amount, ci.amount + 1)
    end
    ci
  end
  
  def remove(artwork_id)
    ci = cart_items.find_by_artwork_id(artwork_id)
    
    if ci.amount > 1
      ci.update_attribute(:amount, ci.amount - 1)
    else
      cart_items.destroy(ci)
    end
    return ci
  end

  def self.to_dollar_amount cost
    format "%0.02f", cost
  end
  
end
